<?php
/**
 * Created by PhpStorm.
 * User: 36980
 * Date: 2017/09/11
 * Time: 11:07
 */

namespace Admin\Controller;

use Think\Controller;

class DownloadController extends Controller
{
    public function index()
    {

        DownloadController::select();
        $this->display();
    }

    public function select()
    {
        $model = M('Download');
        $list = $model->where()->select();
        $this->list = $list;


    }

    public function insert()
    {
        $download = M('Download');
        if (!IS_POST) {
            $this->display();
        }
        if (IS_POST) {
            $num = M('Download')->where("isshow = 1")->count();
            if ($num + $_POST['isshow'] >= 5) {
                $this->error('展示最多展示四个请取消其他');
            }
            $data = DownloadController::postByDownload();
            $data['addtime'] = date("Y-m-d H:i:s");
            if ($download->data($data)->add()) {
                $this->success('添加成功', U('Download/index'));
            } else {
                $this->error('添加失败');
            }


        }

    }

    public function update()
    {
        $id = I('id');
        $download = M('Download');
        if (!IS_POST) {

            $download = M('Download')->where("id = $id")->find();
            $this->post = $download;
            $this->display();
        }
        if (IS_POST) {


            $num = M('Download')->where("isshow = 1")->count();
            $copy = M('Download')->where("id=$id")->find();
            if ($copy['isshow'] != 1) {
                if ($num + $_POST['isshow'] >= 5) {
                    $this->error('展示最多展示四个请取消其他');
                }
            }
            $data = DownloadController::postByDownload();

            if ($download->where("id=$id")->data($data)->save() !== false) {
                $this->success('修改成功', U('Download/index'));
            } else {
                $this->error('修改失败');
            }

        }
    }

public
function delete()
{
    $id = I('id');
    $download = M('Download');
    $modle = $download->where("id=$id")->delete();
    if ($modle) {
        $this->success('修改成功', U('Download/index'));

    } else {
        $this->error('删除失败');
    }

}

public
function postByDownload()
{

    if (!preg_match("/^[1-9][0-9]*$/", $_POST['downum'])) {
        $this->error('请输入整数');
    }
    if (empty($_POST['giftsnum'])) {
        $_POST['giftsnum'] = 0;
    } else {
        if (!preg_match("/^[1-9][0-9]*$/", $_POST['giftsnum'])) {
            $this->error('请输入整数');
        }
    }
    if (!is_numeric($_POST['giftsnum'])) {
        $this->error('请输入正确的金额');
    }
    $data['downum'] = $_POST['downum'];//购买次数

    $data['giftsnum'] = $_POST['giftsnum'];//赠送次数
    $data['price'] = $_POST['price'];//购买金额
    $data['remarks'] = $_POST['remarks'];//版本级别
    if (empty($_POST['isshow'])) {
        $_POST['isshow'] = 0;
    }

    $data['isshow'] = $_POST['isshow'];//是否展示 --- 只能展示四个
    return $data;
}
}